package com.my.algorithmlearning.leetcode;

import org.springframework.util.Assert;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName ValidBracket
 * @Description ValidBracket
 * @Author wanghaiwei
 * @Date 2022/11/21 9:30
 */
public class ValidBracket {
    public boolean isValidByStack(String s) {
        Map<Character, Character> brackets = new HashMap<Character, Character>(){{
            put(')','(');
            put(']','[');
            put('}','{');
        }};
        Deque<Character> sequenceQue = new ArrayDeque<>();
        for (int i = 0; i < s.length(); i++) {
            Character c = s.charAt(i);
            if(brackets.containsKey(c)) {
                if(sequenceQue.isEmpty() || sequenceQue.peek() != (Character) brackets.get(c)) {
                    return false;
                }
                sequenceQue.pop();
            }else {
                sequenceQue.push(c);
            }
        }
        return sequenceQue.isEmpty();
    }

    public boolean isValidByRecursive(String s) {
        String newStr = s.replaceAll("\\(\\)|\\[\\]|\\{\\}", "");
        if (s.equals(newStr)) {
            return newStr.isEmpty();
        }
        return isValidByRecursive(newStr);
    }

    public boolean isValid(String s) {
        return isValidByRecursive(s);
    }

    public static void main(String[] args) {
        ValidBracket solution = new ValidBracket();
        Assert.isTrue(!solution.isValid("([)]"), "([)]是false");
        Assert.isTrue(solution.isValid("([{}])"), "([{}])是true");
        Assert.isTrue(solution.isValid("([{}]){}"), "([{}]){}是true");
        Assert.isTrue(solution.isValid("(()[]{})"), "([{}]){}是true");
    }
}
